﻿using System.Windows.Controls;
using System.Windows.Media.Imaging;
using AzukiMap.Map;
using AzukiMap.MapSource;
using AzukiMap.Tools.Logger;
using Geotools.Geometries;
using System.Xml.Linq;

namespace AzukiMap.Layer
{
    public class WMSLayer : RasterLayer
    {
        WMSSource _wmsMapSource;

        public WMSLayer(WMSSource wmsMapSource, MapCanvas mapCanvas, string name, GTPolygon maxExtent)
            : base(wmsMapSource, mapCanvas, name,maxExtent)
        {
            init(wmsMapSource);
        }

        public WMSLayer(WMSSource wmsMapSource, MapCanvas mapCanvas, string name)
            : base(wmsMapSource, mapCanvas, name)
        {
            init(wmsMapSource);
        }

        void init(WMSSource wmsMapSource)
        {
            _wmsMapSource = wmsMapSource;
        }

        public override void Draw()
        {
            if (! CheckMaxExtent() || ! CheckScale() || ! IsVisible)
            {
                Logger.Debug("WMSLayer.Draw(): Drawing was skipped.");
                return;
            }
            _wmsMapSource.Width = GetOutputWidth();
            _wmsMapSource.Height = GetOutputHeight();
            _wmsMapSource.Bbox = _mapCanvas.CurrentExtent.GetEnvelopeInternal();
            BitmapImage imageSource = new BitmapImage(_wmsMapSource.ImageUri);
            
            Image wmsImage = new Image();
            double offsetX = _mapCanvas.AdjX * -1 + _wmsMapSource.GetImageOffsetX();
            double offsetY = _mapCanvas.AdjY * -1 + _wmsMapSource.GetImageOffsetY();
            wmsImage.SetValue(Canvas.LeftProperty, offsetX);
            wmsImage.SetValue(Canvas.TopProperty, offsetY);
            wmsImage.Source = imageSource;
            
            _mapCanvas.Children.Add(wmsImage);
        }

        int GetOutputWidth()
        {
            return (int)(_mapCanvas.ScreenWidth + _bufferWidth * 2);
        }

        int GetOutputHeight()
        {
            return (int)(_mapCanvas.ScreenHeight + _bufferHeight * 2);
        }

        public override XElement ToXml()
        {
            return ToXml("WMSLayer");
        }

        public override XElement ToXml(string elementName)
        {
            return base.ToXml(elementName);
        }
    }
}
